import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.LayoutManager;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.Stack;

import javax.swing.BoxLayout;
import javax.swing.GroupLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.JToolBar;
import javax.swing.Timer;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.border.MatteBorder;

public class UIMain extends JFrame implements MouseListener {

	Image source;
	Image image;
	int columns = 33; // 33 is the optimum on the laptop
	int rows = 33;
	int[][] pos;
	int width, height;
	ArrayList<JLabel> labelList = new ArrayList<JLabel>();
	public static int goal;
	int numberOfHumans = 2;
	ArrayList<Integer> goalList = new ArrayList();
	int numbernode = 0;
	Image humanImage;
	public static int xCor, yCor;
	static ArrayList<Human> humansList = new ArrayList<Human>();
	String blockerType = "wall";
	Human human;
	boolean complete = false;
	ArrayList<Stack> pathNodesList = new ArrayList<Stack>();
	int speed = 1;
	Timer timer;
	JPanel panel;
	
	public UIMain() {

		JMenuBar menuBar = new JMenuBar();
		setJMenuBar(menuBar);

		JMenu mnFile = new JMenu("File");
		menuBar.add(mnFile);

		JMenuItem mntmNew = new JMenuItem("New");
		mnFile.add(mntmNew);

		JMenuItem mntmExit = new JMenuItem("Exit");
		mnFile.add(mntmExit);

		JToolBar toolBar = new JToolBar();
		toolBar.setAlignmentX(Component.LEFT_ALIGNMENT);
		toolBar.setFloatable(false);
		getContentPane().add(toolBar, BorderLayout.NORTH);

		JButton btnRun = new JButton("");
		btnRun.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
				if (complete == true) {
					movementOfHumans(this);
				}
			}
		});

		btnRun.setIcon(new ImageIcon(UIMain.class
				.getResource("/images/run-copy-icon.png")));
		toolBar.add(btnRun);

		JButton btnStop = new JButton("");
		btnStop.setIcon(new ImageIcon(UIMain.class
				.getResource("/images/Actions-process-stop-icon.png")));
		toolBar.add(btnStop);

		JSplitPane splitPane = new JSplitPane();
		getContentPane().add(splitPane, BorderLayout.CENTER);

		panel = new JPanel();
		panel
				.setBorder(new MatteBorder(1, 1, 1, 1, (Color) new Color(0, 0,
						0)));
		splitPane.setLeftComponent(panel);
		panel.setLayout(new GridLayout(rows + 1, columns));
		panel.setMaximumSize(new Dimension(columns * width, height * rows));
		drawUI(panel);

		JPanel panel_1 = new JPanel();
		panel_1.setBorder(new MatteBorder(1, 1, 1, 1,
				(Color) new Color(0, 0, 0)));

		splitPane.setRightComponent(panel_1);

		JButton btnChair = new JButton("");
		btnChair.setToolTipText("Chair");
		btnChair.setIcon(new ImageIcon(UIMain.class
				.getResource("/images/btnImageChair.png")));
		btnChair.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				blockerType = "chair";
			}
		});

		JButton btnTable = new JButton("");
		btnTable.setToolTipText("Table");
		btnTable.setIcon(new ImageIcon(UIMain.class
				.getResource("/images/TableImages.jpg")));
		btnTable.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				blockerType = "table";
			}
		});

		JButton btnWall = new JButton("");
		btnWall.setToolTipText("Wall");
		btnWall.setIcon(new ImageIcon(UIMain.class
				.getResource("/images/cellChangeBtnImage.JPG")));
		btnWall.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				blockerType = "wall";
			}
		});

		JLabel lblBlockerTypes = new JLabel("Obstacle Types");

		JButton btnComplete = new JButton("Complete");
		btnComplete.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				complete = true;
				for (int i = 0; i < numberOfHumans; i++) {
					Stack<Node> pathNodes = new Stack<Node>();
					pathNodes.addAll(humansList.get(i).getPath(humansList.get(i).getStartNode(), goalList));
					pathNodesList.add(pathNodes);
					humansList.get(i).setPathNodeCount(pathNodes.size());
				}
			}
		});
		GroupLayout gl_panel_1 = new GroupLayout(panel_1);
		gl_panel_1
				.setHorizontalGroup(gl_panel_1
						.createParallelGroup(Alignment.LEADING)
						.addGroup(
								gl_panel_1
										.createSequentialGroup()
										.addGap(23)
										.addGroup(
												gl_panel_1
														.createParallelGroup(
																Alignment.LEADING)
														.addComponent(
																btnComplete)
														.addComponent(
																lblBlockerTypes)
														.addGroup(
																gl_panel_1
																		.createSequentialGroup()
																		.addComponent(
																				btnChair,
																				GroupLayout.PREFERRED_SIZE,
																				44,
																				GroupLayout.PREFERRED_SIZE)
																		.addGap(
																				18)
																		.addComponent(
																				btnTable,
																				GroupLayout.PREFERRED_SIZE,
																				42,
																				GroupLayout.PREFERRED_SIZE)
																		.addPreferredGap(
																				ComponentPlacement.UNRELATED)
																		.addComponent(
																				btnWall,
																				GroupLayout.PREFERRED_SIZE,
																				40,
																				GroupLayout.PREFERRED_SIZE)))
										.addContainerGap(464, Short.MAX_VALUE)));
		gl_panel_1.setVerticalGroup(gl_panel_1.createParallelGroup(
				Alignment.LEADING).addGroup(
				gl_panel_1.createSequentialGroup().addContainerGap()
						.addComponent(lblBlockerTypes).addGap(11).addGroup(
								gl_panel_1.createParallelGroup(
										Alignment.TRAILING, false)
										.addComponent(btnChair,
												Alignment.LEADING,
												GroupLayout.PREFERRED_SIZE, 40,
												Short.MAX_VALUE).addComponent(
												btnTable, Alignment.LEADING,
												GroupLayout.PREFERRED_SIZE, 40,
												Short.MAX_VALUE).addComponent(
												btnWall, Alignment.LEADING,
												GroupLayout.PREFERRED_SIZE, 40,
												GroupLayout.PREFERRED_SIZE))
						.addGap(28).addComponent(btnComplete).addGap(433)));
		panel_1.setLayout(gl_panel_1);

		setTitle("Panic UI");
		setSize(columns * width, height * rows);
		setResizable(true);
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setVisible(true);
	}

	public void drawUI(JPanel drawPanel) {
		Graph graph = new Graph();
		graph.createLocations(0, columns, 0, rows, 1);
		graph.createGrid();
		graph.createAdjMatrix();

		JLabel label;

		pos = new int[rows][columns];
		int counter = 0;
		for (int i = 0; i < rows; i++) {
			for (int j = 0; j < columns; j++) {
				pos[i][j] = counter;
				counter++;
			}
		}
		ImageIcon sid = new ImageIcon(this.getClass().getResource(
				"images/cell.jpg"));
		source = sid.getImage();
		width = sid.getIconWidth();
		height = sid.getIconHeight();

		getContentPane().setLayout(
				(LayoutManager) new BoxLayout(getContentPane(),
						BoxLayout.Y_AXIS));

		int counters = 0;

		for (int i = 0; i < rows; i++) {
			for (int j = 0; j < columns; j++) {
				label = new JLabel(Integer.toString(counters));
				label.addMouseListener(this);
				label.setSize(width, height);
				drawPanel.add(label);
				drawPanel.setSize(width, height);
				image = createImage(source.getSource());
				label.setIcon(new ImageIcon(image));
				counters++;
				labelList.add(label);
			}
		}

		for (int i = 0; i < numberOfHumans; i++) {
			getHumanStartLocations(i);
		}

	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		new UIMain();
	}

	public void setDefaultStartIcon(int humanNumber) {
		JLabel startLabel = null;
		startLabel = labelList.get(humansList.get(humanNumber).getStartNode());
		ImageIcon imageChange = new ImageIcon(UIMain.class
				.getResource("images/cell.jpg"));
		source = imageChange.getImage();
		image = createImage(source.getSource());
		startLabel.setIcon(new ImageIcon(image));
	}

	public void getHumanStartLocations(int humanNumber) {

		JLabel startLabel = null;
		int startLocation = 0;
		human = new Human();
		startLocation = human.getStartLocations(columns, rows, labelList);
		human.setHumanNumber(humanNumber);
		human.setStartNode(startLocation);
		startLabel = labelList.get(human.getStartNode());
		ImageIcon imageChange = new ImageIcon(this.getClass().getResource(
				"images/ppl1.png"));
		source = imageChange.getImage();
		image = createImage(source.getSource());
		startLabel.setIcon(new ImageIcon(image));
		humansList.add(human);
	}

	public void mouseClicked(MouseEvent e) {
		// TODO Auto-generated method stub

	}

	public void mouseEntered(MouseEvent e) {
		// TODO Auto-generated method stub
	}

	public void mouseExited(MouseEvent e) {
		// TODO Auto-generated method stub
	}

	public void mousePressed(MouseEvent e) {
		// TODO Auto-generated method stub
	}

	public void mouseReleased(MouseEvent e) {
		// TODO Auto-generated method stub
		setGoalLocations(e);
	}

	public void setGoalLocations(MouseEvent e) {
		JLabel labels = (JLabel) e.getSource();
		Dimension size = labels.getSize();
		Graph graph = new Graph();

		int labelX = labels.getX();
		int labelY = labels.getY();
		int labelPosX = labelX / size.width;
		int labelPosY = labelY / size.height;
		int labelIndex = pos[labelPosY][labelPosX];
		int blocker;
		if (e.isPopupTrigger()) {
			ImageIcon imageChange = null;
			if (blockerType.equals("chair")) {
				imageChange = new ImageIcon(UIMain.class
						.getResource("images/resizedChair.png"));
			} else if (blockerType.equals("table")) {
				imageChange = new ImageIcon(UIMain.class
						.getResource("images/resizedTable.png"));
			} else if (blockerType.equals("wall")) {
				imageChange = new ImageIcon(UIMain.class
						.getResource("images/cellChange.JPG"));
			}
			blocker = labelIndex;
			source = imageChange.getImage();
			image = createImage(source.getSource());
			labels.setIcon(new ImageIcon(image));

			graph.removeAdjacencies(blocker);
		} else {
			goal = labelIndex;
			ImageIcon imageChange = new ImageIcon(UIMain.class
					.getResource("images/cellGoal.JPG"));
			source = imageChange.getImage();
			image = createImage(source.getSource());
			labels.setIcon(new ImageIcon(image));
			goalList.add(goal);
		}
	}

	public void paint(Graphics g) {
		super.paint(g);
		Graphics2D g2d = (Graphics2D) g;
		for(int i=0;i<numberOfHumans;i++){	
			for(int j=0;j<humansList.get(i).xList.size();j++){
				g2d.drawImage(humanImage, (Integer)humansList.get(i).xList.get(j), (Integer)humansList.get(i).yList.get(j), this);
				Toolkit.getDefaultToolkit().sync();
				g.dispose();
			}
		}
	}

	public void movementOfHumans(ActionListener a) {
		int nodeNumber = 0;

		if(numbernode == 0){
			for(int i=0;i<numberOfHumans;i++){		
				speed = 150;
				timer = new Timer(speed, a);
				timer.start();
				setDefaultStartIcon(humansList.get(i).getHumanNumber());

			}
			numbernode++;
		}else{
			for(int i=0;i<numberOfHumans;i++){				
				JLabel labels = null;

				Stack<Node> paths = pathNodesList.get(i);
				for(int j=0;j<paths.size();j++){
				nodeNumber = paths.get(humansList.get(i).getCurrentNode()).nodeNum;
				labels = labelList.get(nodeNumber);
				humansList.get(i).setCurrentNode((humansList.get(i).getCurrentNode()+1));
				xCor = labels.getLocation().x + 5;
				yCor = labels.getLocation().y + 100;
				
				humansList.get(i).xList.add(xCor);
				humansList.get(i).yList.add(yCor);
				}
				ImageIcon imageChange = new ImageIcon(UIMain.class
						.getResource("images/ppl1.png"));
				humanImage = imageChange.getImage();
			}

			repaint();	
		}
	}
}
